package demo2;

import java.util.concurrent.*;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 石方旭
 * Date: 2022-08-03
 * Time: 14:43
 */
//实现一个线程池
public class MyThreadPool {

       //队列用来存放任务同时要保证线程安全
    private BlockingQueue<Runnable> queue = new LinkedBlockingQueue<>();
    private void submit(Runnable runnable){
        try {
            queue.put(runnable);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    private Runnable runnable;
    public MyThreadPool(int nThreads){
        for(int i =0;i<nThreads;++i){
            Thread t = new Thread(()->{
                while(!Thread.currentThread().isInterrupted()){
                    try {
                        Runnable runnable = queue.take();
                        runnable.run();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
            t.start();
        }
    }

    public static int cnt =0;
    public static void main(String[] args) {
        // ExecutorService e = Executors.newFixedThreadPool(10);
        MyThreadPool e = new MyThreadPool(10);
        for(int i =0;i<100;++i){
            e.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println("hello");
                }
            });
            cnt++;
        }
        System.out.println("总共执行的hello 数量" + cnt);

    }
}
